<?php

class BlogController extends BaseController
{
    public function __construct()
    {
    	// prevents re-login.
        $this->beforeFilter('guest', ['only' => ['getLogin']]);
        $this->beforeFilter('auth', ['only' => ['getLogout']]);
    }

    /**
     * 
     */
    public function getIndex()
    {
        $posts = Post::orderBy('id', 'desc')->paginate(2);

        $posts->getFactory()
        	  ->setViewName('pagination::slider'); // or option with 'simple'
        
        $this->layout->title = 'Home Page | Laravel 4 Blog';
        $this->layout->main = View::make('home')->nest('content', 'index', compact('posts'));
    }

    /*
     We will use the getSearch() action to provide the search functionality on the blog. In this action we are querying the Post model for the search terms. The whereRaw() method is used to specify a MySQL fulltext search criteria, the matching results are then retrieved using the paginate() method to enable the pagination on the resulting models. Also, we need to append the search query to the pagination links. Otherwise, pagination on search results will not work. This is done using the $post->appends() method call.
     */
//     public function getSearch()
//     {
//         $searchTerm = Input::get('s');
//         $posts = Post::whereRaw('match(title,content) against(? in boolean mode)', [$searchTerm])
//             ->paginate(10);
//         $posts->getFactory()->setViewName('pagination::slider');
//         $posts->appends(['s' => $searchTerm]);
//         $this->layout->with('title', 'Search: ' . $searchTerm);
//         $this->layout->main = View::make('home')
//             ->nest('content', 'index', ($posts->isEmpty()) ? ['notFound' => true] : compact('posts'));
//     }

    /**
     * 
     */
    public function getLogin()
    {
        $this->layout->title = 'login';
        $this->layout->main = View::make('login');
    }

    /**
     * 
     */
    public function postLogin()
    {
        $credentials = [
            'username' => Input::get('username'),
            'password' => Input::get('password')
        ];
        $rules = [
            'username' => 'required',
            'password' => 'required'
        ];
        $validator = Validator::make($credentials, $rules);
        if ($validator->passes()) {
            if (Auth::attempt($credentials)) {
                return Redirect::to('admin/dash-board');
            }
            return Redirect::back()->withInput()
            					   ->with('failure', 'username or password is invalid!');
        } else {
            return Redirect::back()->withErrors($validator)
                   				   ->withInput();
        }
    }

    /**
     * 
     */
	public function getLogout()
    {
    	Auth::logout();
        return Redirect::to('/');
    }

}
